package com.leiyuee.designpattern.singletion;

// 单例模式
public class Singleton {
    public static void main(String[] args) {
        LazySingleton instance = LazySingleton.getInstance();
        LazySingleton instance1 = LazySingleton.getInstance();
        HungrySingleton instance3 = HungrySingleton.getInstance();

        InnerClassSingleton instance2 = InnerClassSingleton.getInstance();
    }
}


/**
 * 懒汉: 线程安全问题 ,加锁优化 编译器(JIT)  会指令重排序:尽可能的优化程序正常运行下的逻辑,哪怕以catch()块逻辑变得复杂为代价 volatile
 */
class LazySingleton {
    private volatile static LazySingleton instance;

    private LazySingleton() {
    }

    public synchronized static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                if (instance == null) {
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }
}

/**
 * 饿汉:
 * 类加载: 加载二进制数据到内存中,生成对应的Class数据结构,
 * 连接:验证,准备(给类的静态变量赋 默认值),解析
 * 初始化: 给类的静态变量赋 初值
 */
class HungrySingleton {
    private volatile static HungrySingleton hungrySingleton;

    private HungrySingleton() {
    }

    public static HungrySingleton getInstance() {
        return hungrySingleton;
    }
}

/**
 * 静态内部类
 * 使用了内部类的调用getinstance()方法的时候才会调用
 */

class InnerClassSingleton {
    private static class InnerClassHolder {
        private volatile static InnerClassSingleton instance = new InnerClassSingleton();
    }

    private InnerClassSingleton() {
    }

    public static InnerClassSingleton getInstance() {
        return InnerClassHolder.instance;
    }
}